package com.banzhi.shop.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.banzhi.shop.R;

import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.data.PartnerCheckstandData;
import com.banzhi.shop.data.ShowCreditData;
import com.banzhi.shop.demo.PayResult;
import com.banzhi.shop.entity.Checkstand.WXPay_Data;
import com.banzhi.shop.model.CallBack.CheckStandCallBack;
import com.banzhi.shop.model.CallBack.PartnerCheckstandCallBack;
import com.banzhi.shop.model.CallBack.ShowCreditCallBack;
import com.banzhi.shop.model.Impl.CheckStandImpl;
import com.banzhi.shop.model.Impl.CheckStandImpl2;
import com.banzhi.shop.model.Impl.PartnerCheckstandImpl;
import com.banzhi.shop.model.Impl.ShowCreditImpl;

import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;

import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;

import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.util.Map;

import static com.banzhi.shop.MyApp.APP_ID;

//收银台(城市合伙人)
public class PartnerCheckstandActivity extends BaseActivity implements View.OnClickListener, PartnerCheckstandCallBack,ShowCreditCallBack, CheckStandCallBack,Handler.Callback {

    private ImageView mIvBackCheckstand;
    //成为城市合伙人要交1000元
    private TextView mTvPartner;
    //支付账号余额
    private TextView mTvYuePartner;
    private LinearLayout mLl_weixin;
    private LinearLayout mLl_zhifubao;
    private LinearLayout mLl_yue;
    private PartnerCheckstandImpl mModel;
    private PartnerCheckstandData mPartnerCheckstandData;
    private ShowCreditImpl mCreditModel;
    private ShowCreditData mCreditData;
    private CheckStandImpl2 mCheckStandModel;
    private PartnerCheckstandData mPartnerCheckstandWXData;
    //微信订单号
    private String mWXordersn;
    private PartnerCheckstandData mPartnerCheckstandZFBData;
    //支付宝订单号
    private String mZFBordersn;

    /**
     * 微信支付实体类
     */
    private WXPay_Data pay;
    private Handler handler;
    /**
     * 注册广播接受者
     */
    private Receiver receiver;
    private String mYue0rdersn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_partner_checkstand);
        Translucent.setTranslucent(this);
        mModel = new PartnerCheckstandImpl();
        mCheckStandModel = new CheckStandImpl2();
        mCreditModel = new ShowCreditImpl();
        mCreditModel.ShowCredit(this);
       /*支付方式 24微信支付 22支付宝 支付 1余额支付*/
        mModel.PayWX("24",this);
        mModel.PayZFB("22",this);
        mModel.PayYure("1",this);
        handler = new Handler(this);
        // 注册广播接受者
        receiver = new Receiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.banzhi");
        registerReceiver(receiver, filter);
        initView();
        initListener();

    }

    private void initView() {
        mIvBackCheckstand = (ImageView) findViewById(R.id.iv_back_checkstand);
        mTvPartner = (TextView) findViewById(R.id.tv_price);
        mTvYuePartner = (TextView) findViewById(R.id.tv_yue_partner);
        mLl_weixin = (LinearLayout) findViewById(R.id.ll_weixingzhifu);
        mLl_zhifubao = (LinearLayout) findViewById(R.id.ll_zhifubao);
        mLl_yue = (LinearLayout) findViewById(R.id.ll_pay_yue);
    }
    private void showViews() {
     /*   if (ASUtils.isCanUse(mCreditData.getData().getCitpartnerMoney())) {
            mTvPartner.setText(mCreditData.getData().getCitpartnerMoney());
        }*/
            mTvPartner.setText(mCreditData.getData().getCitpartnerMoney());
            mTvYuePartner.setText(mCreditData.getData().getCredit());


        //获取ordersn订单号
    }

    private void initListener() {
        mIvBackCheckstand.setOnClickListener(this);
        mLl_weixin.setOnClickListener(this);
        mLl_zhifubao.setOnClickListener(this);
        mLl_yue.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back_checkstand:
                finish();
                break;
            case R.id.ll_weixingzhifu:
                LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                mCheckStandModel.PayWX(mWXordersn, mCreditData.getData().getCitpartnerMoney(), this);
                break;
            case R.id.ll_zhifubao:
                LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                mCheckStandModel.PayZFB(mZFBordersn, mCreditData.getData().getCitpartnerMoney(), this);
                break;
            case R.id.ll_pay_yue:
                showPopupWindow(view);
                break;
        }
    }

    private void showPopupWindow(View view) {
        View contentView = LayoutInflater.from(PartnerCheckstandActivity.this).inflate(R.layout.popumwindow_yu_e, null);
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = WindowManager.LayoutParams.MATCH_PARENT;
        final PopupWindow popupWindow = new PopupWindow(contentView, width, height);
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);//允许在外点击消失
        //设置各个控件 的点击相应
        TextView tvCancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                LoadingDialogUtils.showProgress(PartnerCheckstandActivity.this, "正在加载,请稍后~");

                mCheckStandModel.PayYure( mYue0rdersn,mCreditData.getData().getCitpartnerMoney(),PartnerCheckstandActivity.this);

                popupWindow.dismiss();
            }
        });

        View rootView = LayoutInflater.from(PartnerCheckstandActivity.this).inflate(R.layout.activity_commodity_details, null);
        popupWindow.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    //余额支付成功获取//获取ordersn订单号
    @Override
    public void onPayYuePartnerSuccess(Object object) {
        mPartnerCheckstandData = (PartnerCheckstandData) object;
        mYue0rdersn = mPartnerCheckstandData.getData().getOrdersn();
        ToastUtils.makeToastShort(mPartnerCheckstandData.getMsg());



    }
    //余额支付失败
    @Override
    public void onPayYuePartnerError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onPayYureSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        Intent intent = new Intent(this, AuditStateActivity.class);
        intent.putExtra("check","0");
        startActivity(intent);
        finish();

    }

    @Override
    public void onPayYureError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }
    //微信支付成功
    @Override
    public void onPayWXSuccess(Object object) {
        pay = (WXPay_Data) object;
        WeChatPay(pay);
    }

    private void WeChatPay(WXPay_Data data) {
        if (null == data) {
            //判断是否为空。丢一个toast，给个提示。比如服务器异常，错误啥的
            ToastUtils.makeToastShort("服务器异常");
            return;
        }
        IWXAPI api = WXAPIFactory.createWXAPI(this, APP_ID);
        if (!api.isWXAppInstalled()) {
            ToastUtils.makeToastShort("没有安装微信");
        }
        if (!api.isWXAppSupportAPI()) {
            ToastUtils.makeToastShort("当前版本不支持支付功能");
        }
        //data  根据服务器返回的json数据创建的实体类对象
        PayReq req = new PayReq();
        req.appId = data.getAppid();
        req.partnerId = data.getPartnerid();
        req.prepayId = data.getPrepayid();
        req.packageValue = "Sign=WXPay";
        req.nonceStr = data.getNoncestr();
        req.timeStamp = data.getTimestamp();
        req.sign = data.getSign();
        api.registerApp(APP_ID);
        //发起请求
        api.sendReq(req);

    }
    //微信支付失败
    @Override
    public void onPayWXError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }
    //支付宝付款成功
    @Override
    public void onPayZFBSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        final String orderInfo = jsonObject.optString("data");

        new Thread() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PartnerCheckstandActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = 2;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        }.start();

    }
    //支付宝付款失败
    @Override
    public void onPayZFBError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    @Override
    public void onPayWXPartnerSuccess(Object object) {
        mPartnerCheckstandWXData = (PartnerCheckstandData) object;
        //获取微信订单号
        mWXordersn = mPartnerCheckstandWXData.getData().getOrdersn();

    }

    @Override
    public void onPayWXPartnerError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    @Override
    public void onPayZFBPartnerSuccess(Object object) {
        mPartnerCheckstandZFBData = (PartnerCheckstandData) object;
        //获取支付宝订单号
        mZFBordersn = mPartnerCheckstandZFBData.getData().getOrdersn();
    }

    @Override
    public void onPayZFBPartnerError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }
    //成功获取余额信息
    @Override
    public void onShowCreditSucess(Object object) {
        LogUtils.d("onShowCreditSucess",object.toString());
        mCreditData = (ShowCreditData) object;
        showViews();

    }
    //获取余额信息失败
    @Override
    public void onShowCreditError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    @Override
    public boolean handleMessage(Message msg) {
        ToastUtils.makeToastShort("获取订单中...");
        switch (msg.what) {
            case 2:
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String resultInfo = payResult.getResult();
                String resultStatus = payResult.getResultStatus();
                if (TextUtils.equals(resultStatus, "9000")) {
                    ToastUtils.makeToastShort("支付成功");
                    Intent intent = new Intent(this, AuditStateActivity.class);
                    intent.putExtra("check","0");
                    startActivity(intent);
                    finish();
                } else {
                    if (TextUtils.equals(resultStatus, "8000")) {
                        ToastUtils.makeToastShort("支付结果确认中");
                    } else {
                        ToastUtils.makeToastShort("支付失败");
                    }
                }
                break;

        }
        return false;
    }


    public class Receiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("com.banzhi".equals(action)) {
                ToastUtils.makeToastShort("支付成功");
                Intent wxintent = new Intent(PartnerCheckstandActivity.this, AuditStateActivity.class);
                wxintent.putExtra("check","0");
                startActivity(wxintent);
                finish();
            }
        }
    }
    @Override
    public void onDestroy() {
        // 注销广播接受者
        unregisterReceiver(receiver);
        super.onDestroy();
    }




}
